package leetcode_day._2021._202105._1120;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/5/14 22:30
 * 整数转罗马数字
 * 算法：字符串
 * 先把数字的各十百千给求出来
 * 主要跟 5 和 10 对比
 */
public class _14_12 {
    public static void main(String[] args) {
        System.out.println(new _14_12().intToRoman(9));
    }

    public String intToRoman(int num) {
        Map<Integer, String> dic = new HashMap<>();
        dic.put(1, "I");
        dic.put(5, "V");
        dic.put(10, "X");
        dic.put(50, "L");
        dic.put(100, "C");
        dic.put(500, "D");
        dic.put(1000, "M");
        int digit = 1;
        StringBuilder ans = new StringBuilder();
        while (num != 0) {
            int cur = num % 10 * digit;
            StringBuilder tmp = new StringBuilder();
            if (cur < 4 * digit) for (int i = digit; i <= cur; i += digit) tmp.append(dic.get(digit));
            else if (cur == 4 * digit) tmp.append(dic.get(digit)).append(dic.get(5 * digit));
            else if (cur == 5 * digit) tmp.append(dic.get(5 * digit));
            else if (cur < 9 * digit) {
                tmp.append(dic.get(5 * digit));
                for (int i = digit; i <= cur - 5 * digit; i += digit) tmp.append(dic.get(digit));
            } else if (cur == 9 * digit) tmp.append(dic.get(digit)).append(dic.get(cur + digit));
            digit *= 10;
            num /= 10;
            ans.insert(0, tmp);
        }
        return ans.toString();
    }

    public String intToRoman_perfect(int num) {
        String[] x = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        Integer[] y = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < x.length; i++) {
            while (num >= y[i]) {
                ans.append(x[i]);
                num -= y[i];
            }
        }
        return ans.toString();
    }

}
